import { useRef, useEffect } from "react";
import type { FC } from "react";
import type { ChatMessage } from "../types/chat";
import MessageList from "./MessageList";
import InputArea from "./InputArea";
import type { InputAreaRef } from "./InputArea";
import type { AiModelResponse } from "../services/chat/geiAiModel";
import EmptyState from "./EmptyState";
// 定义上传文件类型接口
interface UploadFile {
  id: string;
  file: File;
  previewUrl?: string;
}

interface ChatAreaProps {
  messages: ChatMessage[];
  isLoading: boolean;
  isStreaming?: boolean; // 是否正在接收流式响应
  onSendMessage: (
    message: string,
    files?: UploadFile[],
    options?: { isWebSearch?: boolean; isDeepThinking?: boolean }
  ) => void;
  onSendWithFiles?: (
    message: string,
    files: UploadFile[],
    options?: { isWebSearch?: boolean; isDeepThinking?: boolean }
  ) => void;
  onFileUpload?: (file: File | File[]) => void;
  onNewChat: () => void;
  hasActiveChat: boolean; // 保留此参数以保持接口一致性
  models: AiModelResponse[];
  selectedModel: AiModelResponse;
  onModelChange: (model: AiModelResponse) => void;
  inputAreaRef?: React.RefObject<InputAreaRef | null>; // 修改类型定义，使其与useRef创建的类型匹配
  setInputText?: (text: string) => void; // 添加设置输入文本的方法
}

const ChatArea: FC<ChatAreaProps> = ({
  messages,
  isLoading,
  isStreaming = false, // 默认为false
  onSendMessage,
  onSendWithFiles,
  onFileUpload,
  onNewChat,
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  hasActiveChat,
  models,
  selectedModel,
  onModelChange,
  inputAreaRef,
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  setInputText,
}) => {
  // 创建对消息容器的引用
  const messagesContainerRef = useRef<HTMLDivElement>(null);

  // 平滑滚动到底部的函数
  const scrollToBottom = () => {
    if (messagesContainerRef.current) {
      const container = messagesContainerRef.current;

      // 先尝试查找底部锚点元素
      const bottomAnchor = container.querySelector("#chat-bottom-anchor");

      if (bottomAnchor) {
        // 如果存在底部锚点元素，使用更精确的滚动方式
        bottomAnchor.scrollIntoView({
          behavior: "smooth",
          block: "end",
        });
      } else {
        // 回退到传统的滚动方式
        container.scrollTo({
          top: container.scrollHeight,
          behavior: "smooth",
        });
      }
    }
  };

  // 当消息变化或新聊天被选中时，滚动到底部
  useEffect(() => {
    if (messages.length > 0) {
      // 为了确保所有消息（包括可能的图片）都已加载，添加一个短暂延迟
      setTimeout(scrollToBottom, 100);

      // 为了处理图片加载延迟的情况，再添加一个较长的延迟
      setTimeout(scrollToBottom, 500);
    }
  }, [messages]);

  return (
    <div className="flex-1 flex flex-col w-full h-full overflow-hidden">
      {/* 消息列表区域 - 添加ref引用 */}
      <div
        ref={messagesContainerRef}
        className="flex-1 overflow-y-auto overflow-x-hidden min-h-0 max-w-full"
      >
        <div className="w-full max-w-7xl mx-auto px-4 md:px-6 lg:px-8">
          {messages.length > 0 ? (
            <MessageList
              messages={messages}
              isStreaming={isStreaming} // 传递流式状态到 MessageList
              isLoading={isLoading} // 传递加载状态
            />
          ) : (
            <EmptyState onNewChat={onNewChat} setInputText={setInputText} />
          )}
        </div>
      </div>

      {/* 输入区域 - 固定在底部 */}
      <div className="flex-shrink-0 w-full max-w-7xl mx-auto px-4 md:px-6 lg:px-8">
        <InputArea
          ref={inputAreaRef} // 传递ref
          isLoading={isLoading || isStreaming} // 在流式响应时也禁用输入
          onSendMessage={(message, files, options) => {
            onSendMessage(message, files, options);
            // 发送消息后也滚动到底部
            setTimeout(scrollToBottom, 100);
          }}
          onSendWithFiles={
            onSendWithFiles
              ? (message, files, options) => {
                  onSendWithFiles(message, files, options);
                  // 发送消息后也滚动到底部
                  setTimeout(scrollToBottom, 100);
                }
              : undefined
          }
          onFileUpload={onFileUpload}
          models={models}
          selectedModel={selectedModel}
          onModelChange={onModelChange}
        />
      </div>
    </div>
  );
};

export default ChatArea;
